﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using WABingTranslateAPI.Tool;

namespace WABingTranslateAPI
{
        
    /// <summary>
    /// 缓存外部资源到本地，翻译接口
    /// </summary>
    public class CacheIntoLocal2 : IHttpHandler
    {

        string _key1 = "BingTranslate.js";
        string _url1 = @"http://www.microsoftTranslator.com/ajax/v3/WidgetV3.ashx?siteData=ueOIGRSKkd965FeEGM5JtQ**";

        public void ProcessRequest(HttpContext context)
        {

            /*
             * http://www.microsofttranslator.com/ajax/v3/WidgetV3.ashx?siteData=ueOIGRSKkd965FeEGM5JtQ**&amp;ctf=False&amp;ui=true&amp;settings=undefined&amp;from=zh-CHS
             * 
             * http%3A%2F%2Fwww.microsofttranslator.com%2Fajax%2Fv3%2FWidgetV3.ashx%3FsiteData%3DueOIGRSKkd965FeEGM5JtQ**%26amp%3Bctf%3DFalse%26amp%3Bui%3Dtrue%26amp%3Bsettings%3Dundefined%26amp%3Bfrom%3Dzh-CHS
             */


            bool noCeche = false;
            if (!string.IsNullOrEmpty(context.Request.QueryString["noceche"]))
            {
                noCeche = true;
            }

            if (!string.IsNullOrEmpty(context.Request.QueryString["otherurl"]))
            {

                string url = context.Request.QueryString["otherurl"];


                if (url == _key1)//otherurl=BingTranslate.js
                {
                    string keyCache = "CacheIntoLocal2_" + _key1;
                    if (!noCeche)
                    {
                        if (context.Cache[keyCache] != null)
                        {
                            string redata = context.Cache[keyCache].ToString();

                            context.Response.Write(redata);
                            context.Response.End();
                            return;
                        }
                    }

                    //string data = WebTool.GetWebData(_url1);
                    string data = WebTool.DownloadString(_url1);
                    string start = "window['_mstConfig']={appId:'";
                    string end = "',rootURL:'";
                    //string target = "appId: '";
                    //string targetEnd = "',rootURL:'";

                    string datatemp = "";
                    if (!string.IsNullOrEmpty(data))
                    {
                        int index1 = data.IndexOf(start);
                        int index2 = data.IndexOf(end);

                        if (index2 > index1)
                        {
                            datatemp = data.Substring(index1 + start.Length, index2 - (index1 + start.Length));
                        }
                        string path = context.Server.MapPath("/MT/UIC/" + _key1);
                        if (File.Exists(path))
                        {
                            string filedata = File.ReadAllText(path);
                            int indexf1 = filedata.IndexOf(start);
                            int indexf2 = filedata.IndexOf(end);

                            if (indexf2 > indexf1)
                            {

                                string filedate2 = filedata.Substring(indexf1 + start.Length, indexf2 - (indexf1 + start.Length));
                                filedata = filedata.Replace(filedate2, datatemp);
                                context.Cache.Insert(keyCache, filedata, null, DateTime.Now.AddHours(3), System.Web.Caching.Cache.NoSlidingExpiration);

                                File.WriteAllText(path, filedata);
                                context.Response.Write(filedata);
                                context.Response.End();
                                return;

                            }
                        }

                        //int index3 = data.IndexOf(target);
                        //int index4 = data.IndexOf(targetEnd);
                        //if (index2 > index4 && index4 > index3 && index3 > index1)
                        //{
                        //    data = data.Substring(index3 + target.Length, index4 - target.Length + 1);
                        //}
                    }

                    context.Response.Write(data);
                    context.Response.End();
                    return;
                }
                
                string re = "";
                if (HttpRuntime.Cache[url] != null)
                {
                    var rec = HttpRuntime.Cache[url];
                    if (rec != null)
                    {
                        re = rec.ToString();
                    }
                    else
                    {
                        re = WebTool.DownloadString(url);
                        string temp = WebTool.UrlDecode(url);

                          HttpRuntime.Cache.Insert(url, temp, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(3, 0, 0));
                    }
                }
                else
                {
                    re = WebTool.DownloadString(url);
                    string temp = WebTool.UrlDecode(url);
    HttpRuntime.Cache.Insert(url, temp, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(3, 0, 0));
                }


                context.Response.Write(re);
                context.Response.End();
                return;
            }

            context.Response.Write("");
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}